package com.business.app.wechat.login.controller;


import com.business.app.wechat.login.dto.LoginResultDTO;
import com.business.app.wechat.login.service.WeChatLoginService;
import com.business.app.wechat.login.vo.LoginResultVO;
import com.seed.core.controller.AppBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 微信接口
 *
 * @author gchiaway
 * 日期: 2018-12-31
 * 时间: 20:49
 */
@Slf4j
@Api(value = "WeChatController", tags = "WeChatController")
@Controller
@RequestMapping("/app/v1/WeChatController")
public class WeChatController extends AppBaseController {

    /**
     * 微信登录service
     */
    private final WeChatLoginService weChatLoginService;

    @Autowired
    public WeChatController(WeChatLoginService weChatLoginService) {
        this.weChatLoginService = weChatLoginService;
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "app登录")
    public LoginResultVO login(@RequestBody String code) {
        log.info("[api-v1]WeChatLoginController.微信登录");

        LoginResultVO loginResultVO = new LoginResultVO();
        if (StringUtils.isEmpty(code)) {
            loginResultVO.setSuccess(false);
            loginResultVO.setMsg("code不能为空");
            return loginResultVO;
        }
        String openid = weChatLoginService.getOpenId(code);
        if (StringUtils.isEmpty(openid)) {
            loginResultVO.setSuccess(false);
            loginResultVO.setMsg("获取用户openid出现错误!");
            return loginResultVO;
        }
        LoginResultDTO loginResultDTO = weChatLoginService.login(openid);
        //没注册
        if (!loginResultDTO.getRegistered()) {
            loginResultVO.setRegistered(false);
            loginResultVO.setSuccess(false);
            loginResultVO.setMsg(loginResultDTO.getMsg());
            return loginResultVO;
        }
        //登录失败了
        if (!loginResultDTO.getSuccess()) {
            loginResultVO.setSuccess(false);
            loginResultVO.setMsg(loginResultDTO.getMsg());
            return loginResultVO;
        }
        loginResultVO.setOpenid(loginResultDTO.getOpenid());
        loginResultVO.setToken(loginResultDTO.getToken());
        loginResultVO.setUserId(loginResultDTO.getUserId());
        return loginResultVO;
    }

}
